package ab

import (
	"fmt"
	"net/http"
	"sync"
	"time"
)

type Config struct {
	Concurrency   int
	TotalRequests int
	Timeout       time.Duration
}

type Result struct {
	TotalTime      time.Duration
	RequestsPerSec float64
	StatusCodes    map[int]int
	LatencyMetrics struct {
		Min time.Duration
		Max time.Duration
		Avg time.Duration
	}
}

func RunTest(url string, config Config) (*Result, error) {
	client := &http.Client{
		Timeout: config.Timeout,
	}

	var wg sync.WaitGroup
	sem := make(chan struct{}, config.Concurrency)

	// ... 初始化统计数据结构 ...

	start := time.Now()

	for i := 0; i < config.TotalRequests; i++ {
		wg.Add(1)
		sem <- struct{}{}

		go func() {
			defer wg.Done()
			defer func() { <-sem }()

			// reqStart := time.Now()
			resp, err := client.Get(url)
			if err != nil {
				//... 处理错误...
				return
			}
			defer resp.Body.Close()
			// 由于 latency 变量声明后未使用，暂时移除该声明
			// time.Since(reqStart) 调用也一并移除，避免不必要的计算
			//... 更新统计数据...
			//... 打印或记录请求结果...

			//... 处理响应...

			//... 处理错误...
		}()
	}

	wg.Wait()
	totalTime := time.Since(start)
	result := Result{
		TotalTime: totalTime,
		//... 计算其他指标...
	}

	// ... 计算结果指标 ...

	return &result, nil
}

func (r *Result) Report() string {
	return fmt.Sprintf("总耗时: %v\n每秒请求数: %.2f\n状态码分布: %v\n延迟指标: 最小 %v, 最大 %v, 平均 %v",
		r.TotalTime, r.RequestsPerSec, r.StatusCodes, r.LatencyMetrics.Min, r.LatencyMetrics.Max, r.LatencyMetrics.Avg)
	// ... 生成格式化报告 ...
}
